package com.punai.config.sqlitedao.impl;


import com.punai.common.exception.ServiceException;
import com.punai.common.utils.sqlite.SqliteUtil;
import com.punai.config.sqlitedao.StructureLinkTemplateRepository;
import com.punai.config.sqlitedomain.StructureLinkTemplate;
import com.punai.config.sqlitesetting.SqliteSystemTemplConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class StructureLinkTemplateRepositoryImpl implements StructureLinkTemplateRepository {
    private static SqliteUtil sqliteUtil;
    private static final Logger log = LoggerFactory.getLogger(StructureLinkTemplateRepository.class);

    @Autowired
    private SqliteSystemTemplConnection sqliteSystemTemplConnection;

    private void initConnection() {
        sqliteUtil = sqliteSystemTemplConnection.initConnection();
    }

    @Override
    public void save(StructureLinkTemplate link)  {
        this.delete(link.getTemplateId(),link.getStrutsId());
        initConnection();
        String Sql = " insert into "
                + "tab_config_link_strut_template(template_id,struts_id) "
                + "values(?,?)";
        Object[] args = new Object[]{
                link.getTemplateId(),
                link.getStrutsId()
        };
        int rownumber = sqliteUtil.execute(Sql, args);
        if (rownumber == 0) {
            throw new ServiceException("sqlite.message.addException");
        }
    }

    @Override
    public void deleteByStrutsId(String struts_id) {

    }

    @Override
    public void deleteByTemplateId(String template_id) {

    }

    @Override
    public void delete(String template_id, String struts_id) {
        initConnection();
        String Sql = "delete from tab_config_link_strut_template "+
                "where " +
                "template_id = '"+ template_id+"' " +
                "and struts_id = '" + struts_id + "' ";
        int rownumber = sqliteUtil.execute(Sql);
    }

  @Override
  public List<StructureLinkTemplate> findByTemplateId(String id) {
    initConnection();

    String sql = "select * from tab_config_link_strut_template where template_id = '"+ id +"' ";
    List<StructureLinkTemplate> record = sqliteUtil.selectListRecord(StructureLinkTemplate.class, sql);
    return record;
  }
}
